<?php

declare(strict_types=1);

namespace App\Service;

use App\Models\Agent;
use App\Models\AgentRevenue;
use App\Models\AgentRewardRuleSettings;
use App\Models\AgentTopUpOrder;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;

class PaymentBusinessService
{
    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @Inject()
     * @var AgentRewardRuleSettingsService
     */
    protected $agentRewardRuleSettingsService;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 充值订单成功后的操作
     * @param $outTradeNo string 业务订单号
     */
    public function topUp($outTradeNo)
    {
        $agentTopUpOrder = AgentTopUpOrder::query()
            ->with('agent')
            ->where('order_id', $outTradeNo)
            ->firstOrFail();

        $rewardSetting = $this->agentRewardRuleSettingsService->rewardSetting(AgentRewardRuleSettings::TYPE_RECHARGE_BONUS); // 奖励设置

        /** @var Agent $agent */
        $agent = $agentTopUpOrder->agent;

        $reachTheThreshold = array_filter($rewardSetting, fn($setting) => $agentTopUpOrder['amount'] >= $setting['threshold_amount']); // 达到门槛的配置
        if (!empty($reachTheThreshold)) {
            // 排序配置
            uasort($reachTheThreshold, function ($current, $next) {
                $compared = $current['threshold_amount'] <=> $next['threshold_amount']; // 优先按照门槛值排序 (高的在前)
                if ($compared === 0) {
                    return $current['reward'] <=> $next['reward']; // 当门槛值相同时,按照奖励值排序 (高的在前)
                }

                return $compared;
            });
            $setting = end($reachTheThreshold); // 排完序后,最大的在最后

            $agent->incrementOrDecrementUnextractableBalance($agentTopUpOrder['amount'], AgentRevenue::TYPE_TOP_UP_UNEXTRACTABLE, $agentTopUpOrder); // 加充值的钱
            $agent->incrementOrDecrementUnextractableBalance($setting['reward'], AgentRevenue::TYPE_TOP_UP_GIVE_AWAY, $agentTopUpOrder); // 加奖励的钱
        } else {
            $agent->incrementOrDecrementBalance($agentTopUpOrder['amount'], AgentRevenue::TYPE_TOP_UP, $agentTopUpOrder); // 加充值的钱
        }
    }
}
